package com.sdhs.projectschedule.service.impl;

import java.util.List;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.google.gson.JsonObject;
import com.sdhs.businessfile.domain.BusinessFile;
import com.sdhs.businessfile.service.IBusinessFileService;
import com.sdhs.common.core.domain.event.ProcessEvent;
import com.sdhs.common.enums.BusinessStatusEnum;
import com.sdhs.common.enums.BusinessTypeEnum;
import com.sdhs.common.utils.*;
import com.sdhs.listmanage.domain.entity.GcManageList;
import com.sdhs.listmanage.domain.vo.GcProjectManageListVo;
import com.sdhs.myproject.domain.GcMyprojectInformation;
import com.sdhs.myproject.service.IGcMyprojectInformationService;
import com.sdhs.projectschedule.domain.GcProgressConstructionLog;
import com.sdhs.projectschedule.domain.GcProgressHandIn;
import com.sdhs.projectschedule.mapper.GcProgressHandInMapper;
import com.sdhs.projectschedule.service.IGcProgressHandInService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;


/**
 * 项目进度控制--项目交工Service业务层处理
 *
 * @author andong
 * @date 2025-03-11
 */
@Service
public class GcProgressHandInServiceImpl implements IGcProgressHandInService
{
    @Autowired
    private GcProgressHandInMapper gcProgressHandInMapper;

    @Autowired
    private IBusinessFileService businessFileService;
    @Autowired
    private IGcMyprojectInformationService gcInformationService;
    /**
     * 查询项目进度控制--项目交工
     *
     * @param id 项目进度控制--项目交工主键
     * @return 项目进度控制--项目交工
     */
    @Override
    public GcProgressHandIn selectGcProgressHandInById(Long id)
    {
        GcProgressHandIn gcProgressHandIn = gcProgressHandInMapper.selectGcProgressHandInById(id);
        List<BusinessFile> businessFiles = businessFileService.listByBusinessTypeAndId(BusinessTypeEnum.GC_PROGRESS_HAND_IN.getCode(), String.valueOf(id));
        gcProgressHandIn.setFileList(businessFiles);
        return gcProgressHandIn;
    }

    /**
     * 查询项目进度控制--项目交工列表
     *
     * @param gcProgressHandIn 项目进度控制--项目交工
     * @return 项目进度控制--项目交工
     */
    @Override
    public List<GcProgressHandIn> selectGcProgressHandInList(GcProgressHandIn gcProgressHandIn)
    {
        return gcProgressHandInMapper.selectGcProgressHandInList(gcProgressHandIn);
    }

    /**
     * 新增项目进度控制--项目交工
     *
     * @param gcProgressHandIn 项目进度控制--项目交工
     * @return 结果
     */
    @Override
    public GcProgressHandIn insertGcProgressHandIn(GcProgressHandIn gcProgressHandIn)
    {
        gcProgressHandIn.setCreater(SecurityUtils.getUsername());
        gcProgressHandIn.setCreateTime(DateUtils.getNowDate());
        gcProgressHandIn.setApprovalStatus(BusinessStatusEnum.DRAFT.getStatusValue());
        gcProgressHandInMapper.insertGcProgressHandIn(gcProgressHandIn);
        handler(gcProgressHandIn.getId(), gcProgressHandIn);
        return gcProgressHandIn;
    }

    /**
     * 修改项目进度控制--项目交工
     *
     * @param gcProgressHandIn 项目进度控制--项目交工
     * @return 结果
     */
    @Override
    public int updateGcProgressHandIn(GcProgressHandIn gcProgressHandIn)
    {
        gcProgressHandIn.setUpdater(SecurityUtils.getUsername());
        gcProgressHandIn.setUpdateTime(DateUtils.getNowDate());
        int i = gcProgressHandInMapper.updateGcProgressHandIn(gcProgressHandIn);
        handler(gcProgressHandIn.getId(), gcProgressHandIn);
        return i;
    }
    /**
     * 项目进入缺陷责任期
     *
     * @return 结果
     */
    @Override
    public int updatePeriod(GcProgressHandIn gcProgressHandIn)
    {
        int i = gcProgressHandInMapper.updatePeriod(gcProgressHandIn);
        GcMyprojectInformation gcMyprojectInformation = new GcMyprojectInformation();
        gcMyprojectInformation.setId(gcProgressHandIn.getProjectId());
        gcMyprojectInformation.setProjectStatus("7");
        /*修改项目状态为缺陷责任期*/
        gcInformationService.updateGcMyProject(gcMyprojectInformation);

        /*推送安全项目开始*/
        if (gcProgressHandIn.getProjectId()!=null){
            JsonObject jsonObject = new JsonObject();
            jsonObject.addProperty("engineeringId", gcProgressHandIn.getProjectId()); //项目id
            jsonObject.addProperty("type", "update"); //类型
            jsonObject.addProperty("status", "7"); //项目状态-交工
            try {
                String jsonData = jsonObject.toString(); // 直接转为JSON字符串
                String encryptedData = AESUtils.encrypt(jsonData);
                /*推送安全接口*/
                SafetyUtil.pushUrl(encryptedData);
            } catch (JsonProcessingException e) {
                System.err.println("JSON序列化失败: " + e.getMessage());
                throw new RuntimeException(e);
            } catch (Exception e) {
                System.err.println("加密失败: " + e.getMessage());
                throw new RuntimeException(e);
            }
        }
        /*推送安全项目结束*/
        return i;
    }
    /**
     * 批量删除项目进度控制--项目交工
     *
     * @param ids 需要删除的项目进度控制--项目交工主键
     * @return 结果
     */
    @Override
    public int deleteGcProgressHandInByIds(Long[] ids)
    {
        return gcProgressHandInMapper.deleteGcProgressHandInByIds(ids);
    }

    /**
     * 删除项目进度控制--项目交工信息
     *
     * @param id 项目进度控制--项目交工主键
     * @return 结果
     */
    @Override
    public int deleteGcProgressHandInById(Long id)
    {
        GcProgressHandIn gcProgressHandIn = gcProgressHandInMapper.selectGcProgressHandInById(id);
        gcProgressHandIn.setIsDelete("1");
        return gcProgressHandInMapper.updateGcProgressHandIn(gcProgressHandIn);
    }

    /*项目交工审批监听*/
    @org.springframework.context.event.EventListener(condition = "#processEvent.key.startsWith('progress_hand_in')")
    public void processHandler(ProcessEvent processEvent) {

        // 已完成（已通过）
        if (BusinessStatusEnum.FINISH.getStatus().equals(processEvent.getStatus())) {
            String businessKey = processEvent.getBusinessKey();
             GcProgressHandIn gcProgressHandIn = gcProgressHandInMapper.selectGcProgressHandByInstanceId(businessKey);
             GcMyprojectInformation gcMyprojectInformation = new GcMyprojectInformation();
             gcMyprojectInformation.setId(gcProgressHandIn.getProjectId());
             gcMyprojectInformation.setProjectStatus("3");
                /*修改项目状态为已交工*/
             gcInformationService.updateGcMyProject(gcMyprojectInformation);
          /*获取项目交工信息中是否有商机id，如果有商机id的话，将信息推送到营销项目中*/
            if (gcProgressHandIn.getBusinessId()!=null){

                JsonObject jsonObject = new JsonObject();
                jsonObject.addProperty("businessId", gcProgressHandIn.getBusinessId());
                jsonObject.addProperty("statusId", "3");
                jsonObject.addProperty("isOrganization", gcProgressHandIn.getIsOrganization());
                try {
                    String jsonData = jsonObject.toString(); // 直接转为JSON字符串
                    String encryptedData = AESUtils.encrypt(jsonData);
                    /*推送营销接口*/
                    PushUtil.pushUrl(encryptedData);
                } catch (JsonProcessingException e) {
                    System.err.println("JSON序列化失败: " + e.getMessage());
                    throw new RuntimeException(e);
                } catch (Exception e) {
                    System.err.println("加密失败: " + e.getMessage());
                    throw new RuntimeException(e);
                }
            }

            /*推送安全项目开始*/
            if (gcProgressHandIn.getProjectId()!=null){
                JsonObject jsonObject = new JsonObject();
                jsonObject.addProperty("engineeringId", gcProgressHandIn.getProjectId()); //项目id
                jsonObject.addProperty("type", "update"); //类型
                jsonObject.addProperty("status", "3"); //项目状态-交工
                try {
                    String jsonData = jsonObject.toString(); // 直接转为JSON字符串
                    String encryptedData = AESUtils.encrypt(jsonData);
                    /*推送安全接口*/
                    SafetyUtil.pushUrl(encryptedData);
                } catch (JsonProcessingException e) {
                    System.err.println("JSON序列化失败: " + e.getMessage());
                    throw new RuntimeException(e);
                } catch (Exception e) {
                    System.err.println("加密失败: " + e.getMessage());
                    throw new RuntimeException(e);
                }
            }
            /*推送安全项目结束*/
        }

    }
    /**
     * 保存联合数据
     * 保存合同附件
     */
    public void handler(Long id, GcProgressHandIn gcProgressHandIn) {
        // 保存合同附件
        businessFileService.saveFileBatch(BusinessTypeEnum.GC_PROGRESS_HAND_IN.getCode(), String.valueOf(id), gcProgressHandIn.getFileList());
    }
}
